﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net;
using System.Threading;
using Microsoft.WindowsAzure;
using Microsoft.WindowsAzure.Diagnostics;
using Microsoft.WindowsAzure.ServiceRuntime;
using Microsoft.WindowsAzure.StorageClient;
using System.ServiceModel;
using HelloService;

namespace WorkerRole1
{
    public class WorkerRole : RoleEntryPoint
    {
        private ServiceHost host;

        public override void Run()
        {
            Trace.WriteLine("WorkerRole1 entry point called", "Information");

            while (true)
            {
                Thread.Sleep(10000);
                Trace.WriteLine("Working", "Information");
            }
        }

        public override bool OnStart()
        {
            ServicePointManager.DefaultConnectionLimit = 12;

            StartWCFService();

            return base.OnStart();
        }

        public override void OnStop()
        {

            try
            {
                // if WCF service was opened then i'm going to close it
                if (host != null && host.State == CommunicationState.Opened)
                    host.Close();
            }
            catch(Exception ex) {
                Trace.WriteLine("Exception: " + ex.Message, "Information");
            }

            base.OnStop();
        }


        /// <summary>
        /// Initialize the WCF service
        /// </summary>
        private void StartWCFService()
        {
            try
            {
                IPEndPoint ipEndPoint = RoleEnvironment.CurrentRoleInstance.InstanceEndpoints["HelloService"].IPEndpoint;
                host = new ServiceHost(typeof(HellloService));
                NetTcpBinding binding = new NetTcpBinding(SecurityMode.None);
                host.AddServiceEndpoint(typeof(IHellloService), binding, String.Format("net.tcp://{0}/HellloService", ipEndPoint));

                host.Open();
            }
            catch (Exception ex)
            {
                Trace.WriteLine(ex.Message, "Error");
                throw;
            }
            Trace.WriteLine("WCF Hello service running...");
        }

        /// <summary>
        /// Stop the WCF service
        /// </summary>
        private void StopWCFService()
        {
            if (host != null)
            {
                try
                {
                    host.Close();
                }
                catch (Exception ex)
                {
                    Trace.WriteLine(ex.Message, "Error");
                    host.Abort();
                    throw;
                }
            }
        }
    }
}
